package cn.tedu.web.ycw.Servlet;


import cn.tedu.web.ycw.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

import static javafx.scene.input.KeyCode.J;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求中键名为 u 的值
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("u");
        // 获取请求中键名为 p 的值
        String password = req.getParameter("p");
        // 获取请求中键名为 c 的值
        String code = req.getParameter("c");

        System.out.println(username);
        System.out.println(password);
        System.out.println(code);
        HttpSession session = req.getSession();
        Object yzm = session.getAttribute("yzm");
        boolean isTrue = yzm != null && code != null && code.equals(yzm);
        if(!isTrue){
            PrintWriter writer = resp.getWriter();
            writer.write("验证码错误，仔细点！");
            writer.flush();
            writer.close();
            return;
        }

        // TODO
        // 在此处通过 JDBC 来检查前端传递的 username 和 password 在数据库中是否存在
        // 如果存在，在页面显示登录成功，否则显示登录失败
        String sql = "SELECT * FROM `user` WHERE username = ? AND `password` = MD5(?)";
        Long id = JdbcUtils.select(sql, Long.class, username,password);
        if (id != null){
            session.setAttribute("UID",id);
            //登录成功，去首页 http://localhost:8080
            resp.sendRedirect("/ycw/");
        }else{
            //登录失败，去登录页
            resp.sendRedirect("/ycw/login.jsp");
        }
        String message =id !=null && id>0L ? "登陆成功!":"登录失败！";
        PrintWriter writer = resp.getWriter();
        writer.write(message);
        writer.flush();
        writer.close();
    }
}
